package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.common.minio.MinIOFileStorageService;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.ThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author QLJ
 * @since 2022-09-02
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinIOFileStorageService minIOFileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 自媒体上传图片
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //判断文件是否为空
        if (multipartFile == null) {
            throw new LeadNewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //获取用户
        WmUser wmUser = (WmUser) ThreadLocalUtils.get();
        if (wmUser == null) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            //得到文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String name = multipartFile.getOriginalFilename();
            String extName = name.substring(name.lastIndexOf("."));
            String fileName = uuid + extName;

            //上传图片
            String url = minIOFileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());

            //写入DB
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(wmUser.getId());        //设置用户id
            wmMaterial.setUrl(url);                      //设置图片地址
            wmMaterial.setCreatedTime(new Date());       //设置创建时间
            wmMaterial.setIsCollection((short) 0);          //设置不收藏
            wmMaterial.setType((short) 0);                //设置类型
            save(wmMaterial);

            //返回素材信息
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            log.info("上传图片上传图片失败");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询素材集合
     */
    @Override
    public PageResponseResult wmMaterialList(WmMaterialDto wmMaterialDto) {
        //参数校验
        wmMaterialDto.checkParam();

        //判断是否登录（获取登录用户信息）
        WmUser wmUser = (WmUser) ThreadLocalUtils.get();
        if (wmUser == null) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //设置页数，每页有几条
        IPage<WmMaterial> iPage = new Page<>(wmMaterialDto.getPage(),wmMaterialDto.getSize());

        //查询条件
        QueryWrapper<WmMaterial> wmMaterialQueryWrapper = new QueryWrapper<>();

        //判断当前登录用户
        wmMaterialQueryWrapper.eq("user_id",wmUser.getId());

        //是否收藏
        if (wmMaterialDto.getIsCollection()!=null && wmMaterialDto.getIsCollection() == 1) {
            wmMaterialQueryWrapper.eq("is_collection", wmMaterialDto.getIsCollection());
        }

        //按日期倒叙排序
        wmMaterialQueryWrapper.orderByDesc("created_time");

        //分页查询
        iPage = page(iPage, wmMaterialQueryWrapper);


        //封装返回值
        PageResponseResult pageResponseResult = new PageResponseResult(wmMaterialDto.getPage(),wmMaterialDto.getSize(),(int)iPage.getTotal());
        pageResponseResult.setCode(200);
        pageResponseResult.setErrorMessage("查询成功");
        pageResponseResult.setData(iPage.getRecords());

        return pageResponseResult;
    }


    /**
     * 素材收藏
     */
    @Override
    public ResponseResult collect(Integer id) {
        if (id == null){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);                       //素材id
        wmMaterial.setIsCollection((short) 1);        //素材收藏
        updateById(wmMaterial);
        //返回成功结果
        return ResponseResult.setAppHttpCodeEnum(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 素材取消收藏
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        if (id == null){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);                       //素材id
        wmMaterial.setIsCollection((short) 0);        //素材收藏
        updateById(wmMaterial);
        //返回成功结果
        return ResponseResult.setAppHttpCodeEnum(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 删除素材
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        if (id == null){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        QueryWrapper<WmNewsMaterial> wmNewsMaterialQueryWrapper = new QueryWrapper<>();
        wmNewsMaterialQueryWrapper.eq("material_id",id);

        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(wmNewsMaterialQueryWrapper);
        //没关联删除
        if (wmNewsMaterials == null || wmNewsMaterials.size() == 0){
            removeById(id);
            return ResponseResult.setAppHttpCodeEnum(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(501,"删除失败素材有关联");
    }
}
